package com.demo.accessibility.app

import android.app.Activity
import android.app.Application
import android.app.Application.ActivityLifecycleCallbacks
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import java.util.*

/**
 * ================================================
 * 监听activity的生命周期
 * Created by ligang on 2023/3/13 9:10
 * ================================================
 */
class AppStateTracker private constructor() : ActivityLifecycleCallbacks {
    companion object {
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { AppStateTracker() }
        const val STATE_FOREGROUND = 0
        const val STATE_BACKGROUND = 1
    }

    var mCurrentState = STATE_FOREGROUND

    private val mActivityList = LinkedList<Activity>()
    private var resumeActivityCount = 0
    private var mApplication: Application? = null
    private var mAppStateChangeListener: AppStateChangeListener? = null
    fun initTrack(application: Application? = null, listener: AppStateChangeListener? = null) {
        mAppStateChangeListener = listener
        mApplication = application
        application?.let {
            it.registerActivityLifecycleCallbacks(this)
        }
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        mActivityList.add(activity)
    }

    fun isAppForeground(): Boolean {
        return mCurrentState == STATE_FOREGROUND
    }

    fun getTopActivity(): Activity? {
        if (mActivityList.isEmpty()) {
            return null
        }
        return mActivityList.last
    }

    override fun onActivityStarted(activity: Activity) {
        if (resumeActivityCount == 0) {
            mCurrentState = STATE_FOREGROUND
            mAppStateChangeListener?.appTurnIntoForeground()
        }
        resumeActivityCount++
    }

    override fun onActivityResumed(activity: Activity) {

    }

    override fun onActivityPaused(activity: Activity) {
        if (activity.isFinishing) {
            mActivityList.remove(activity)
        }
    }

    override fun onActivityStopped(activity: Activity) {
        resumeActivityCount--
        if (resumeActivityCount == 0) {
            mCurrentState = STATE_BACKGROUND
            mAppStateChangeListener?.appTurnIntoBackGround()
        }
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
    }

    override fun onActivityDestroyed(activity: Activity) {
        unregisterScreenBroadcastReceiver(activity)
    }

    interface AppStateChangeListener {
        /**
         * app转变为前台
         */
        fun appTurnIntoForeground()

        /**
         * app转变为后台
         */
        fun appTurnIntoBackGround()
    }

    private val mBroadcastReceiverMap = mutableMapOf<Context, BroadcastReceiver>()

    fun registerScreenBroadcastReceiver(
        context: Context,
        listener: ScreenLockStatusChangeListener? = null
    ): BroadcastReceiver {
        val broadcastReceiver = object : BroadcastReceiver() {
            val SYSTEM_REASON = "reason"
            val SYSTEM_HOME_KEY = "homekey"
            val SYSTEM_RECENT_APPS = "recentapps"
            override fun onReceive(context: Context?, intent: Intent) {
                when (intent.action) {
                    Intent.ACTION_SCREEN_ON -> { // 开屏
                        listener?.onScreenOn()
                    }
                    Intent.ACTION_SCREEN_OFF -> { // 锁屏
                        listener?.onScreenOff()
                    }
                    Intent.ACTION_USER_PRESENT -> { // 解锁
                        listener?.onScreenUserPresent()
                    }
                    Intent.ACTION_CLOSE_SYSTEM_DIALOGS -> {
                        intent.getStringExtra(SYSTEM_REASON)?.let { reason ->
                            when (reason) {
                                SYSTEM_RECENT_APPS -> {
                                    listener?.onBackHome()
                                }
                                else -> {

                                }
                            }
                        }
                    }
                    else -> {

                    }
                }
            }
        }
        context.registerReceiver(broadcastReceiver, IntentFilter().apply {
            addAction(Intent.ACTION_SCREEN_ON)
            addAction(Intent.ACTION_SCREEN_OFF)
            addAction(Intent.ACTION_USER_PRESENT)
            addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
        })
        mBroadcastReceiverMap[context] = broadcastReceiver
        return broadcastReceiver
    }

    /**
     * 反注册广播
     */
    private fun unregisterScreenBroadcastReceiver(context: Context) {
        mBroadcastReceiverMap[context]?.let {
            context.unregisterReceiver(it)
        }
        if (mBroadcastReceiverMap.containsKey(context)) {
            mBroadcastReceiverMap.remove(context)
        }
    }

    interface ScreenLockStatusChangeListener {
        fun onScreenOn()
        fun onScreenOff()
        fun onScreenUserPresent()
        fun onBackHome()
    }
}